<template>
	<div class="system-menu-container">
		<div class="breadcrumb-box">
			<Breadcrumb />
		</div>

		<div class="header-search">
			<el-input class="search-item" placeholder="请输入序号/姓名/手机号/住院号" v-model="state.apiData.search" size="default"
				style="width: 220px;" clearable @change="searchChange()">
			</el-input>

			<el-select class="search-item" v-model="state.apiData.departmentId" placeholder="请选择科室" size="default"
				style="width: 150px;" clearable @change="searchChange">
				<el-option v-for="(item, index) in state.departmentList" :key="index" :label="item.departmentName"
					:value="item.id"></el-option>
			</el-select>

			<div class="search-date-picker-box search-item">
				<el-date-picker v-model="state.apiData.recordAt" type="daterange" range-separator="至" start-placeholder="录入开始日期"
					end-placeholder="录入结束日期" size="default" value-format="YYYY-MM-DD" @change="recordAtChange" clearable />
			</div>

			<div class="search-date-picker-box search-item">
				<el-date-picker v-model="state.apiData.operationAt" type="daterange" range-separator="至"
					start-placeholder="手术开始日期" end-placeholder="手术结束日期" size="default" value-format="YYYY-MM-DD"
					@change="operationAtChange" clearable />
			</div>

		</div>

		<div class="page-main" v-loading="state.tableData.loading" ref="pageMain">
			<el-card shadow="hover" style="height:100%;">
				<div class="filter-list">
					<div class="filter-item flex align-center" v-for="(item, index) in state.searchBtns" :key="index"
						@click="changeSearch(item.value)" :class="state.apiData.status == item.value ? 'active' : ''">
						<SvgIcon class="icon" :name="item.icon" />
						<span class="name">{{ item.text }} </span>
						<span class="num">{{ '（' + item.total + '）' }} </span>
					</div>
				</div>
				<div class="output-box">
					<el-button @click="goExport()" link size="small" type="primary" style="padding-left:0;">
						<el-icon class="el-icon--right">
							<Download />
						</el-icon>导出患者列表
					</el-button>
				</div>

				<el-table :data="state.tableData.data" border style="width: 100%" :height="state.tableHeight"
					ref="multipleTableRef" @selection-change="handleSelectionChange" @sort-change="handleSortChange"
					@row-click="handleRowClick" :row-style="rowStyle">
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column type="index" label="序号" width="70" align="center" />
					<el-table-column prop="serialNumber" label="日间序号" width="120" show-overflow-tooltip align="center"
						sortable="custom">
						<template #default="scope">
							{{ scope.row.serialNumber ? scope.row.serialNumber : '-' }}
						</template>
					</el-table-column>
					<el-table-column prop="recordAt" label="录入日期" width="120" show-overflow-tooltip align="center"
						sortable="custom">
						<template #default="scope">
							{{ scope.row.recordAt ? formatRecordAt(scope.row.recordAt) : '-' }}
						</template>
					</el-table-column>
					<!-- <el-table-column prop="recordId" label="登记号" width="120" show-overflow-tooltip align="center"
						sortable="custom"></el-table-column> -->
					<el-table-column prop="patientName" label="患者姓名" width="120" show-overflow-tooltip align="center"
						sortable="custom">
						<template #default="scope">
							{{ scope.row.patient.name }}
						</template>
					</el-table-column>
					<el-table-column prop="phone" label="手机号" width="120" show-overflow-tooltip align="center" sortable="custom">
						<template #default="scope">
							{{ scope.row.patient.phone ? scope.row.patient.phone : '-' }}
						</template>
					</el-table-column>
					<!-- <el-table-column prop="patient.identity" label="身份证" width="180" show-overflow-tooltip align="center"></el-table-column> -->
					<el-table-column label="主刀医生" width="90" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ (scope.row.operation && scope.row.operation.chiefDoctor) ? scope.row.operation.chiefDoctor.name : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="麻醉方式" width="120" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ (scope.row.anesthesiaAssessment && scope.row.anesthesiaAssessment.anesthesiaMode) ?
								scope.row.anesthesiaAssessment.anesthesiaMode.name : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="拟行手术" width="230" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ (scope.row.operation && scope.row.operation.operation) ? scope.row.operation.operation.name : '-' }}
						</template>
					</el-table-column>

					<el-table-column prop="operationAt" label="手术日期" width="120" show-overflow-tooltip align="center"
						sortable="custom">
						<template #default="scope">
							{{ scope.row.operation && scope.row.operation.operationAt ? scope.row.operation.operationAt : '-' }}
						</template>
					</el-table-column>
					<el-table-column prop="patient.hospitalId" label="住院号" width="80" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ scope.row.patient && scope.row.patient.hospitalId ? scope.row.patient.hospitalId : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="当前状态" width="120" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ scope.row.status && scope.row.status != 0 ? state.statusObj[scope.row.status] : '-' }}
						</template>
					</el-table-column>
				
					<el-table-column label="手术科室" width="150" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ (scope.row.operation && scope.row.operation.department) ?
								scope.row.operation.department.departmentName : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="申请人" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ (scope.row.visitingDoctor && scope.row.visitingDoctor.name) ? scope.row.visitingDoctor.name : '-' }}
						</template>
					</el-table-column>
					<el-table-column prop="preDiagnosis" width="120" label="诊断" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ scope.row.preDiagnosis ? scope.row.preDiagnosis : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="医保" show-overflow-tooltip width="70" align="center">
						<template #default="scope">
							{{ scope.row.isMedicalInsurance ? '是' : '否' }}
						</template>
					</el-table-column>
				
					<el-table-column label="操作" width="100" fixed="right" align="center">
						<template #default="scope">
							<el-button size="small" link type="primary" @click="goDetail(scope.row.id)">查看</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div v-if="stepObj.stepId" class="step-box">
					<el-steps :active="stepObj.activeStep" align-center process-status="finish">
						<el-step v-for="(item, index) in state.stepList" :key="index" :title="item.text"
							:class="isPassed(item.value) ? 'passed' : ''" />
					</el-steps>
				</div>
				<div class="pagination-box">
					<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
						:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.apiData.page" background
						v-model:page-size="state.apiData.pageSize" layout="total, sizes, prev, pager, next, jumper"
						:total="state.tableData.total">
					</el-pagination>
				</div>

			</el-card>
		</div>


	</div>
</template>

<script setup name="dsProcess-overview">
import { useRouter } from 'vue-router';
import { Download } from '@element-plus/icons-vue'
import { getCurrentInstance } from 'vue';
import { dsApi } from '/@/api/ds/index';
import { toolsApi } from '/@/api/tools/index';
import { sumArr, transListToObj } from '/@/utils/arrayOperation'
import { getHost } from "/@/utils/getHost";
import { Session } from '/@/utils/storage';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs'
import { usePageDatas } from '/@/stores/pageDatas';
import { storeToRefs } from 'pinia'
const pageMain = ref();

const stores = usePageDatas();
const { patientListApiData } = storeToRefs(stores);
// 引入组件
const Breadcrumb = defineAsyncComponent(() => import('/@/layout/navBars/breadcrumb/breadcrumb.vue'));

const router = useRouter();

// 定义变量内容
const state = reactive({
	apiData: {
		page: 1,
		pageSize: 10,
		departmentId: '',
		search: '',
		status: 0,
		type: 1
	},
	apiSortData: null,
	tableData: {
		data: [],
		loading: false,
		total: 0
	},
	tableHeight: '30vh',
	searchBtns: [

	],
	departmentList: [],
	stepList: [],
	statusObj: null,
	statusList: [],
	multipleSelection: [],
	passedStatusList: []
});
const stepObj = reactive({
	stepId: null,
	activeStep: 0, // 从0开始
})
// 页面加载时
onMounted(() => {
	if (patientListApiData.value.page) {
		state.apiData.page = patientListApiData.value.page
	}
	getList()
	getTools()
	state.tableHeight = getCurrentInstance().refs.pageMain.offsetHeight - 130 - 34 - 50 + "px";
});

const searchChange = () => {
	state.apiData.page = 1
	getList()
}

const changeSearch = (e) => {
	state.apiData.status = e
	state.apiData.page = 1
	getList()
}


const handleSelectionChange = (value) => {
	state.multipleSelection = value
}

const handleSortChange = (columns) => {
	console.log(columns)
	if (columns.prop == "serialNumber") { // 日间序号
		if (columns.order) {
			state.apiSortData = {
				patientRecordsSerialNumber: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	} else if (columns.prop == "recordAt") { // 录入日期
		if (columns.order) {
			state.apiSortData = {
				patientRecordsRecordAt: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	} else if (columns.prop == "recordId") { // 登记号
		if (columns.order) {
			state.apiSortData = {
				patientRecordsRecordId: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	} else if (columns.prop == "patientName") { // 患者姓名
		if (columns.order) {
			state.apiSortData = {
				patientsName: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	} else if (columns.prop == "phone") { // 手机号
		if (columns.order) {
			state.apiSortData = {
				patientsPhone: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	} else if (columns.prop == "operationAt") { //手术日期
		if (columns.order) {
			state.apiSortData = {
				patientRecordOperationsOperationAt: columns.order == "ascending" ? 'asc' : 'desc'
			}
		} else {
			state.apiSortData = null
		}
	}

	getList()
}

const handleRowClick = async (row) => {
	// getPatientStatus(row.id)
	const res = await toolsApi().getPatientStatusList({prid: row.id})
	console.log(res)
	state.stepList = res.data
	nextTick(() => {
		state.tableHeight = pageMain.value.offsetHeight - 130 - 34 - 136 - 50 + "px";
	});
	state.passedStatusList = []
	if (row.statusLogs && row.statusLogs.length > 0) {
		let currentStatusList = []
		row.statusLogs.forEach(item => {
			currentStatusList.push(item.status)
		})
		// console.log(currentStatusList)
		state.passedStatusList = arrayAminusB(state.statusList, currentStatusList)
	}


	stepObj.stepId = row.id
	stepObj.activeStep = row.status - 1
}

function arrayAminusB(arrA, arrB) {
	return arrA.filter(v => !arrB.includes(v));
}

// 是否是跳过的
const isPassed = (val) => {
	if (state.passedStatusList.length > 0 && state.passedStatusList.indexOf(val) != -1) {
		return true
	} else {
		return false
	}
}

// 分页改变
const onHandleSizeChange = (val) => {
	state.apiData.pageSize = val;
	getList();
};

const onHandleCurrentChange = (val) => {
	state.apiData.page = val;
	getList();
};

const formatRecordAt = (val) => {
	return dayjs(val).format('YYYY-MM-DD')
}


// 如果当前行index 是点击行，就改变颜色
const rowStyle = ({ row, rowIndex }) => {
	if (row.id == stepObj.stepId) {
		return {
			'background-color': 'var(--el-table-row-hover-bg-color) !important'
		}
	}
}


// 获取列表
const getList = () => {
	state.tableData.loading = true
	stepObj.stepId = null

	let apiData = JSON.parse(JSON.stringify(state.apiData))
	if (state.apiSortData) {
		if (state.apiSortData.patientRecordsSerialNumber) {
			apiData.order = {
				'patientRecords.serialNumber': state.apiSortData.patientRecordsSerialNumber
			}
		} else if (state.apiSortData.patientRecordsRecordAt) {
			apiData.order = {
				'patientRecords.recordAt': state.apiSortData.patientRecordsRecordAt
			}
		} else if (state.apiSortData.patientRecordsRecordId) {
			apiData.order = {
				'patientRecords.recordId': state.apiSortData.patientRecordsRecordId
			}
		} else if (state.apiSortData.patientsName) {
			apiData.order = {
				'patients.name': state.apiSortData.patientsName
			}
		} else if (state.apiSortData.patientsPhone) {
			apiData.order = {
				'patients.phone': state.apiSortData.patientsPhone
			}
		} else if (state.apiSortData.patientRecordOperationsOperationAt) {
			apiData.order = {
				'patientRecordOperations.operationAt': state.apiSortData.patientRecordOperationsOperationAt
			}
		}
	}

	dsApi().patientRecords(apiData).then(res => {
		state.tableData.loading = false
		state.tableData.data = res.data.items
		state.tableData.total = res.data.total
	}).catch(() => {
		state.tableData.loading = false
	})

}

// 患者详情
const goDetail = (id) => {
	router.push({
		path: '/dsProcess/overview/patientDetail',
		query: { id: id },
	});
	stores.setPatientListApiDataPage(state.apiData.page)
}

const recordAtChange = (e) => {
	if (e) {
		state.apiData.recordAt = e
	} else {
		state.apiData.recordAt = []
	}
	getList();
}

const operationAtChange = (e) => {
	if (e) {
		state.apiData.operationAt = e
	} else {
		state.apiData.operationAt = []
	}
	getList();
}

const goExport = () => {
	if (state.multipleSelection.length == 0) {
		ElMessage.warning('请选择需要导出的数据');
	} else {
		const prids = []
		state.multipleSelection.forEach(item => {
			prids.push('&prids[]=' + item.id)
		})

		const url = getHost() + '/patient/export_patient_record_list' + '?token=' + Session.get('token') + prids.join('')
		// console.log('url',url)
		const link = document.createElement('a')
		link.href = url
		link.setAttribute('download', '')
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
	}

}



const getTools = () => {
	getDepartmentList()
	getPatientStatus()
}

const getDepartmentList = () => {
	toolsApi().departmentList({ all: 1 }).then(res => {
		state.departmentList = res.data
	})
}

const getPatientStatus = () => {
	toolsApi().patientStatus().then(res => {
		const statusList = []
		state.stepList = res.data
		state.statusObj = transListToObj(res.data, 'value', 'text')
		res.data.forEach(item => {
			statusList.push(item.value)
		})
		state.statusList = statusList

		const searchBtns = JSON.parse(JSON.stringify(res.data))
		const totalList = []
		searchBtns.forEach(item => {
			item.icon = 'ele-Document'
			totalList.push(item.total)
		})
		searchBtns.unshift({
			text: '全部',
			total: sumArr(totalList),
			value: 0,
			icon: 'ele-Menu'
		})
		state.searchBtns = searchBtns
	})
}
</script>

<style lang="scss" scoped>
.page-main {
	height: calc(100vh - 50px - 106px);
	padding: 10px;
}


.filter-list {
	display: grid;
	grid-template-columns: repeat(10, 1fr);
	gap: 5px 10px;
	border-bottom: 1px solid #EFEFEF;
	padding-bottom: 10px;

	.filter-item {
		cursor: pointer;
		white-space: nowrap;

		&.active {

			.icon,
			.name,
			.num {
				color: #1890FF;
			}
		}

		.icon {
			color: #666;
		}

		.name {
			color: #666;
			margin-left: 5px;
		}

		.num {
			color: #999;
		}
	}
}

.output-box {
	padding: 5px 0;
}

.step-box {
	height: 136px;
	padding-top: 60px;
	// padding: 60px 0 20px;


	// 完成的节点加粗
	:deep() .el-step__head.is-finish {

		.el-step__icon.is-text{
			border: 3px solid #1890FF;
		}
		.el-step__line {
			top: 10px;

			.el-step__line-inner {
				border-width: 2px !important;
			}
		}
	}

	// 跳过的节点 圆变灰
	.passed :deep() .el-step__icon.is-text {
		border: 2px solid #A8ABB2 !important;
	}

	.passed	:deep() .el-step__head.is-finish {
		.el-step__line {
			top: 11px;
			.el-step__line-inner {
				border-width: 1px !important;
			}
		}
	}

	:deep() .el-step__icon-inner {
		display: none !important;
	}

	:deep() .el-step__icon {
		width: 20px;
		height: 20px;
	}

	:deep() .el-step__title.is-finish {
		color: #333 !important;
	}

	:deep() .el-step__title.is-process {
		color: #1890FF !important;

	}

	:deep() .el-step__head.is-process {
		.el-step__icon.is-text {
			border-color: #1890FF !important;
			background-color: #1890FF !important;
		}
	}

	:deep() .el-step__title {
		max-width: 70px;
		white-space: nowrap !important;
	}



	:deep() .el-steps .el-step:nth-child(odd) {
		.el-step__main {
			transform: translateY(-60px);
		}

	}

}
</style>
